package com.broada.apm.utils;

import java.io.File;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.tools.ant.util.FileUtils;
import org.elasticsearch.Version;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.node.internal.InternalSettingsPreparer;
import org.elasticsearch.plugin.deletebyquery.DeleteByQueryPlugin;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.script.groovy.GroovyPlugin;

public class EmbedESServer {
	
	private static final String DEFAULT_DATA_DIRECTORY = "target/elasticsearch-data";

	private org.elasticsearch.node.Node node ;
	private String dataDirectory;

	public EmbedESServer() {
		this(DEFAULT_DATA_DIRECTORY);
	}

	@SuppressWarnings("resource")
	public EmbedESServer(String dataDirectory) {
		this.dataDirectory = dataDirectory;

		Settings.Builder elasticsearchSettings = Settings.settingsBuilder()
				.put("http.enabled", "true")
				.put("path.home", "...")
				.put("network.bind_host", "127.0.0.1")
				.put("http.port", "9200")
				.put("script.inline", true)
                .put("script.indexed", true)
				.put("path.data", dataDirectory);
		Set<Class<? extends Plugin>> classpathPlugins = new HashSet<>();
	    classpathPlugins.add(DeleteByQueryPlugin.class);
	    classpathPlugins.add(GroovyPlugin.class);
	    node = new EsNode(elasticsearchSettings.build(), classpathPlugins).start();
//		node = NodeBuilder.nodeBuilder()
//				.local(true)
//				.settings(elasticsearchSettings.build())
//				.node();
	}

	public Client getClient() {
		return node.client();
	}

	public void shutdown() {
		node.close();
		deleteDataDirectory();
	}

	public void deleteDataDirectory() {
		FileUtils.delete(new File(dataDirectory));
	}
	
	public static void main(String[] args) {
		new EmbedESServer().deleteDataDirectory();
	}
	
}

class EsNode extends org.elasticsearch.node.Node{
    protected EsNode(Settings settings, Collection<Class<? extends Plugin>> plugins) {
        super(InternalSettingsPreparer.prepareEnvironment(settings, null), Version.CURRENT, plugins);
    }
}
